iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
Modern Web

區塊鏈&DAPP介紹系列 第 28

[區塊鏈&DAPP介紹 Day28] Dapp 實戰 留言版 - 2

  • 分享至 

  • xImage
  •  

今天來把剩下的留言板,前端的部分完成吧

先看看 js 的 code

import Web3 from "web3";
import GuestbookArtifact from "../../build/contracts/Guestbook.json";

const App = {
  web3: null,
  account: null,
  meta: null,

  //初始化
  start: async function() {
    const { web3 } = this;

    try {
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = GuestbookArtifact.networks[networkId];
      this.meta = new web3.eth.Contract(
        GuestbookArtifact.abi,
        deployedNetwork.address,
      );

      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];

      this.loadRandomWords();
    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },

  //重新載入文字
  loadRandomWords: async function(number) {
    const { queryGuestbook, getSize } = this.meta.methods;
    const count  = await getSize().call()
    const msgEl = document.getElementById("msg")
    if (count == 0){
      msgEl.innerHTML = "沒有內容"
    }else{
      let random_num = Math.random() * count
      const word  = await queryGuestbook(parseInt(random_num)).call();
      const msg = "內容:"+word[0]
          +" <br /> 來源:"+word[1]
          +" <br /> 時間:"+ formatTime(word[2])
      msgEl.innerHTML = msg
    }
  },

  //儲存文字
  saveWord: async function() {
    const msg = document.getElementById("wordArea").value;
    if (msg.length == 0){
      alert("請留下文字喔")
      return
    }

    let timestamp = new Date().getTime()
    const { save } = this.meta.methods;
    await save(msg, parseInt(timestamp / 1000)).send({ from: this.account });

    this.loadRandomWords();
  },
};
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatTime(timestamp) {
  let date = new Date(Number(timestamp * 1000))
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getMinutes()
  let second = date.getSeconds()
  let fDate = [year, month, day, ].map(formatNumber)
  return fDate[0] + '年' + fDate[1] + '月' + fDate[2] + '日' + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
window.App = App;

window.addEventListener("load", function() {
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to http://127.0.0.1:7545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(
      new Web3.providers.HttpProvider("http://127.0.0.1:7545"),
    );
  }

  App.start();
});

再來是 html code

<!DOCTYPE html>
<html>
<head>
  <title>留言板</title>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
<h1>留言區:</h1>
<div id="msg"></div>
<a href="#" onclick="App.loadRandomWords()" class="btn btn-primary">更新</a>
<br/>
<br/>
<br/>
<textarea rows="3" cols="20" id="wordArea"></textarea>
<br/>
<br/>
<a href="#" onclick="App.saveWord()" class="btn btn-primary">送出</a>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="index.js"></script>
</html>

最後再像之前一樣在 app 資料夾裡下

npm run dev

http://127.0.0.1:8080 就會看到下面畫面,留言板就完成了。

guestbook

上面的 example 有完整版在我的 Github


上一篇
[區塊鏈&DAPP介紹 Day27] Dapp 實戰 留言版 -
下一篇
[區塊鏈&DAPP介紹 Day29] Dapp 實戰 何謂 token
系列文
區塊鏈&DAPP介紹30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言